<template>
  <div>
    <el-dialog
      title="取消合同审核"
      :visible.sync="cancelClickShow"
      width="460px">
      <div style="margin-bottom: 10px;" v-if="info.orderState == -30 && cancelInfo.isPriceOffCancel == 1 && cancelInfo.isContact == 0 && step == 1">
        <div style="display: flex;justify-content: flex-start;align-items: center">
          <span style="padding-right:5px">该订单为【客户降价违约】取消，请先进行</span>
          <el-popover
            placement="bottom"
            width="280"
            trigger="click">
            <el-table :data="cancelInfo.contactList" @row-click="callContact" empty-text="暂无联系人" :row-style="{cursor:'pointer'}">
              <el-table-column width="100" property="contactName" label="联系人">
                <template v-slot="{row}">
                  <span class="pointerStyle">{{ row.contactName }}</span>
                </template>
              </el-table-column>
              <el-table-column width="150" property="contactMobile" label="电话">
                <template v-slot="{row}">
                  <span class="pointerStyle">{{ row.contactMobile }}</span>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="success" size="small" slot="reference">电话回访</el-button>
          </el-popover>
          <span style="padding-left:5px;">或</span>
        </div>

        <div style="padding-top: 10px; padding-bottom: 10px;">
          <el-upload action="https://upload.qiniup.com"
                     :http-request="sliderRequest"
                     :limit="1"
                     accept="audio/*"
                     :on-exceed="onExceed"
                     :file-list="fileList"
                     :before-remove="beforeRemove"
                     :on-remove="onRemove">
            <el-button size="small" type="primary" :disabled="fileList.length>=1">上传电话录音</el-button>
          </el-upload>
        </div>
      </div>

      <el-form :model="cancelClickFrom" size="mini" label-width="80px;"  ref="cancelClickFrom" :rules="rulesCancelClick" v-if="step == 2">
        <div style="margin-bottom: 10px" v-if="info.orderState == -30 && cancelInfo.isPriceOffCancel == 1 && cancelInfo.isContact == 1">
          该订单已经进行过回访，可直接审批
        </div>
        <el-form-item label="审核备注：" prop="remark">
          <el-input v-model="cancelClickFrom.remark" :autosize="{ minRows: 2, maxRows: 6}" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <div v-if="info.orderState == -30 && cancelInfo.isPriceOffCancel == 1 && step == 1">
             <el-button @click="getCancelApplyInfo('update')" :loading="btnLoadingCancel3">获取回访记录</el-button>
             <el-button type="primary" @click="nextStep">下一步</el-button>
          </div>
          <div v-else-if="step == 2">
            <el-button @click="step = 1 " v-if="info.orderState == -30 && cancelInfo.isPriceOffCancel == 1 && cancelInfo.isContact == 0">上一步</el-button>
            <el-button type="danger" @click="cancelNo" :loading="btnLoadingCancel2">拒 绝</el-button>
            <el-button type="success" @click="cancelOk" :loading="btnLoadingCancel">同 意</el-button>
          </div>

      </span>
    </el-dialog>

    <!-- 直接外呼 -->
    <outboundCall ref="outboundCallRef"></outboundCall>
  </div>

</template>
<script>
import {postOrdersprocess,getQiniuToken,cancelApplyInfo} from '@/api/partner'
import outboundCall from '@/views/fms/components/outboundCall.vue';
import {formatDate} from '@/utils/date';
import store from '@/store'

import { mapGetters } from 'vuex'
import axios from "axios";



const defauletCancelClickFrom = {
  remark:'',
  orderId:'',
}
export default {
  name: "cancelClick",
  data(){
    return {
      cancelClickShow:false,
      btnLoadingCancel2:false,
      btnLoadingCancel3:false,
      btnLoadingCancel:false,

      cancelClickFrom:JSON.parse(JSON.stringify(defauletCancelClickFrom)),
      rulesCancelClick:{
        remark:[{required: true, trigger: 'blur' ,message: '请输入备注',}],
      },
      info:{},
      orderId:'',
      fileList:[],
      uploadToken:{
        token:'',
      },
      imgDomain:'',
      cancelInfo:{},
      step:1
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  components : {
    outboundCall
  },
  created() {

  },
  filters: {

  },
  methods:{
    getCancelApplyInfo(type){
      this.btnLoadingCancel3 = true;
      cancelApplyInfo({orderId:this.orderId}).then((res)=>{
        this.cancelInfo = res
        this.btnLoadingCancel3 = false
        if(type == 'update'){
          this.$message({
            message: '已获取该订单最新的回访记录',
            type: 'success'
          });
        }

        if(this.info.orderState == -30 && this.cancelInfo.isPriceOffCancel == 1 && this.cancelInfo.isContact == 0){
          this.step = 1
        }else{
          this.step = 2
        }
      })
    },
    nextStep(){
      if(this.info.orderState == -30 && this.cancelInfo.isPriceOffCancel == 1 && this.cancelInfo.isContact == 0 && this.fileList.length == 0){
        this.$message({
          message: '该订单为【客户降价违约】取消，请先进行电话回访或上传电话录音文件',
          type: 'error'
        });
        return false
      }
      this.step = 2
    },
    // 客户外呼
    callContact(row) {
      this.$refs.outboundCallRef.showPop(row)
    },
    //获取七牛TOKEN
    getUploadToken(){
      getQiniuToken().then((res)=>{
        this.uploadToken.token = res.token;
        this.imgDomain = res.domain
      })
    },
    //上传文件重写
    sliderRequest(upload) {
      // 文件上传自行处理上传
      // 创建FormData对象 添加相关上传参数
      const formData = new FormData()
      // 文件对象
      formData.append('file', upload.file)
      // key 文件名处理，这样的话七牛会识别文件时什么类型
      let timestamp=new Date().getTime();
      var result =/\.[^\.]+/.exec(upload.file.name);
      let fileName = timestamp + upload.file.name
      formData.append('key', fileName)
      // token
      formData.append('token', this.uploadToken.token)//这个postData,要在data数据里面进行定义的，，，我这里调接口使用的是vue的方式
      console.log(this.uploadToken.token)
      // 上传文件
      // onUploadProgress 查看axios文档 https://github.com/axios/axios
      axios.post("https://upload.qiniup.com", formData, {
        onUploadProgress: (event) => {
          // 监听上传进度
          event.percent = event.loaded / event.total * 100
          upload.onProgress(event)
        }
      }).then((response) => {
        console.log("response",response)
        if (response.status === 200) {
          let res = response.data;
          console.log(this.imgDomain+res.key);
          let newFile = this.imgDomain+res.key;
          this.fileList.push({name:newFile,url:newFile});
          console.log("this.fileList",this.fileList)
        }else{
          this.handleAvatarError()
        }
      }).catch((err) => {
        // 调用组件上传失败方法
        this.handleAvatarError()
      })
    },

    handleAvatarError(){
      this.$message({
        message: '上传失败',
        type: 'error'
      });
    },

    preview(file){
      window.open(file.name)
    },

    beforeRemove(file, fileList){
      return this.$confirm('确定删除录音文件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(fileList);
      }).catch(() => {
        reject(false);
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    onRemove(file, fileList){
      this.fileList = fileList
    },
    onExceed(file, fileList){
      this.$message({
        message: '最多上传1个附件',
        type: 'error'
      });
    },
    //显示备注弹窗
    showPop(info){
      this.cancelClickShow = true;
      this.cancelClickFrom = JSON.parse(JSON.stringify(defauletCancelClickFrom))
      this.info = info
      this.orderId = info.orderId
      this.getUploadToken()
      this.getCancelApplyInfo()
      this.fileList = []
    },

    //拒绝合同取消
    cancelNo(){
      if(this.info.orderState == -30 && this.cancelInfo.isPriceOffCancel == 1 && this.cancelInfo.isContact == 0 && this.fileList.length == 0){
        this.$message({
          message: '该订单为【客户降价违约】取消，请先进行电话回访或上传电话录音文件',
          type: 'error'
        });
        return false
      }
      this.$refs['cancelClickFrom'].validate((valid) => {
        if (valid) {
          this. btnLoadingCancel2 = true;
          let data = {};
          data.orderId = this.orderId;
          data.action = 'back';
          data.remark = this.cancelClickFrom.remark;
          if(this.info.orderState == -30 && this.cancelInfo.isPriceOffCancel == 1 && this.cancelInfo.isContact == 0 ){
            data.contactFileUrl = this.fileList[0]['url']
          }
          postOrdersprocess(data).then((res)=>{
            this.btnLoadingCancel2 = false;
            this.$message({
              message: '合同已拒绝取消',
              type: 'success'
            });
            this.cancelClickShow = false
            this.$emit('update',res.nowTime)
          }).catch(()=>{
            this.btnLoadingCancel2 = false;
          })
        }
      })
    },

    //同意合同取消
    cancelOk(){
      if(this.info.orderState == -30 && this.cancelInfo.isPriceOffCancel == 1 && this.cancelInfo.isContact == 0 && this.fileList.length == 0){
        this.$message({
          message: '该订单为【客户降价违约】取消，请先进行电话回访或上传电话录音文件',
          type: 'error'
        });
        return false
      }
      this.$refs['cancelClickFrom'].validate((valid) => {
        if (valid) {
          this.btnLoadingCancel = true;
          let data = {};
          data.orderId = this.orderId;
          data.remark = this.cancelClickFrom.remark;
          if(this.info.orderState == -30){
            data.action = 'cancelOrderCheck';
          }else if(this.info.orderState == -28){
            data.action = 'cancelOrderPurchaseCheck';
          }else if(this.info.orderState == -26){
            data.action = 'cancelOrderPManagerCheck';
          }else if(this.info.orderState == -24){
            data.action = 'cancelOrderBossCheck';
          }
          if(this.info.orderState == -30 && this.cancelInfo.isPriceOffCancel == 1 && this.cancelInfo.isContact == 0 ){
            data.contactFileUrl = this.fileList[0]['url']
          }
          postOrdersprocess(data).then((res)=>{
            this.btnLoadingCancel = false;
            this.cancelClickShow = false
            this.$emit('update',res.nowTime)
          }).catch(()=>{
            this.btnLoadingCancel = false;
          })
        }
      })
    },

  },
}
</script>

<style lang="scss">

</style>
